<template>
  <div class="intro-outro-view">
    <!-- 配置区域 -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <h2>处理配置</h2>
        </div>
      </template>

      <!-- 文件夹路径输入 -->
      <div class="form-item">
        <div class="form-label">视频文件夹路径：</div>
        <el-input v-model="folderPath" placeholder="请输入网络共享文件夹路径，例如：\\server\videos" clearable>
          <template #prepend>
            <el-icon>
              <folder />
            </el-icon>
          </template>
        </el-input>
        <div class="form-tip">填写后台可访问的局域网共享文件夹路径</div>
      </div>

      <!-- 转场效果选择 -->
      <div class="form-item">
        <div class="form-label">转场效果：</div>
        <el-select v-model="transitionEffect" placeholder="请选择转场效果" style="width: 100%">
          <el-option v-for="effect in transitionEffects" :key="effect.value" :label="effect.label"
            :value="effect.value" />
        </el-select>
      </div>
    </el-card>

    <!-- 片头片尾选择面板 - 使用新组件 -->
    <el-row :gutter="20" class="video-selection-row">
      <el-col :span="12">
        <VideoSelectorPanel video-type="opening" v-model="selectedOpeningId" @selection-change="handleOpeningSelection"
          @video-deleted="handleVideoDeleted" @video-set-default="handleVideoSetDefault" />
      </el-col>

      <el-col :span="12">
        <VideoSelectorPanel video-type="ending" v-model="selectedEndingId" @selection-change="handleEndingSelection"
          @video-deleted="handleVideoDeleted" @video-set-default="handleVideoSetDefault" />
      </el-col>
    </el-row>

    <!-- 处理按钮 -->
    <div class="process-actions">
      <el-button type="primary" size="large" @click="processVideos" :loading="processing"
        :disabled="!canProcess || processing">
        开始处理视频
      </el-button>
    </div>

    <!-- 处理结果 -->
    <el-card v-if="processResult" class="result-card">
      <template #header>
        <div class="card-header">
          <h2>处理结果</h2>
          <el-button @click="clearResult" text>清除</el-button>
        </div>
      </template>

      <el-result :icon="processResult.success ? 'success' : 'error'" :title="processResult.success ? '处理成功' : '处理失败'"
        :sub-title="processResult.message">
        <template #extra>
          <div v-if="processResult.success">
            <div class="result-info">
              <strong>输出文件夹：</strong> {{ processResult.output_folder }}
              <el-button type="primary" size="small" :icon="FolderOpened"
                @click="copyFolder(processResult.output_folder)" class="open-folder-btn">
                粘贴
              </el-button>
            </div>
          </div>
        </template>
      </el-result>
    </el-card>
  </div>
</template>

<script>
import { defineComponent, ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Folder, FolderOpened } from '@element-plus/icons-vue';
import VideoSelectorPanel from '@/components/VideoSelectorPanel.vue';
import introOutroService from '@/services/introOutroService';

export default defineComponent({
  name: 'IntroOutroView',
  components: {
    VideoSelectorPanel,
    Folder,
    FolderOpened
  },
  setup() {
    const folderPath = ref('');
    const outputFolder = ref('');
    const transitionEffect = ref('fade');
    const transitionEffects = ref([
      { label: '淡入淡出', value: 'fade' },
      { label: '交叉溶解', value: 'crossfade' },
      { label: '硬切', value: 'cut' }
    ]);

    // 片头片尾选择状态
    const selectedOpeningId = ref(null);
    const selectedEndingId = ref(null);
    const selectedOpeningVideo = ref(null);
    const selectedEndingVideo = ref(null);

    // 处理状态
    const processing = ref(false);
    const processResult = ref(null);

    // 是否可以开始处理
    const canProcess = computed(() => {
      return folderPath.value && (selectedOpeningId.value || selectedEndingId.value);
    });

    // 修改 copyFolder 函数
    const copyFolder = (path) => {
      if (!path) {
        ElMessage.warning('没有可复制的路径');
        return;
      }

      // 检查现代 Clipboard API 是否可用
      if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
        navigator.clipboard.writeText(path)
          .then(() => {
            ElMessage.success(`已复制文件夹路径`);
          })
          .catch(err => {
            console.error('使用 Clipboard API 复制失败:', err);
            fallbackCopyToClipboard(path);
          });
      } else {
        // 如果 Clipboard API 不可用，使用备用方法
        fallbackCopyToClipboard(path);
      }
    };

    // 添加备用复制方法
    const fallbackCopyToClipboard = (text) => {
      const textArea = document.createElement('textarea');
      textArea.value = text;

      // 将文本区域设置为不可见
      textArea.style.position = 'fixed';
      textArea.style.left = '-999999px';
      textArea.style.top = '-999999px';
      textArea.style.opacity = '0';

      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();

      let successful = false;
      try {
        // 尝试执行复制命令
        successful = document.execCommand('copy');
        if (successful) {
          ElMessage.success('已复制文件夹路径');
        } else {
          ElMessage.warning('复制失败，请手动选择并复制路径');
        }
      } catch (err) {
        console.error('execCommand 复制失败:', err);
        ElMessage.error('复制失败，请手动选择并复制路径');
      }

      document.body.removeChild(textArea);

      // 如果复制失败，显示手动复制的对话框
      if (!successful) {
        showManualCopyDialog(text);
      }
    };

    // 显示手动复制对话框
    const showManualCopyDialog = (text) => {
      ElMessageBox.alert(text, '请手动复制此路径', {
        confirmButtonText: '确定',
        callback: () => {
          ElMessage.info('您可以按Ctrl+C手动复制上方的路径');
        }
      });
    };

    // 获取转场效果列表
    const loadTransitionEffects = async () => {
      try {
        const result = await introOutroService.getTransitionEffects();
        if (result.success && result.data) {
          transitionEffects.value = result.data.map(effect => ({
            label: effect.name,
            value: effect.id
          }));
        }
      } catch (error) {
        console.error('获取转场效果失败:', error);
      }
    };

    // 处理片头视频选择
    const handleOpeningSelection = (video) => {
      selectedOpeningVideo.value = video;
    };

    // 处理片尾视频选择
    const handleEndingSelection = (video) => {
      selectedEndingVideo.value = video;
    };

    // 处理视频删除
    const handleVideoDeleted = (video) => {
      ElMessage.success(`视频 "${video.filename}" 已删除`);
    };

    // 处理视频设为默认
    const handleVideoSetDefault = (video) => {
      ElMessage.success(`已将 "${video.filename}" 设为默认${video.type === 'opening' ? '片头' : '片尾'}`);
    };

    // 处理视频
    const processVideos = async () => {
      if (!folderPath.value) {
        ElMessage.warning('请输入视频文件夹路径');
        return;
      }

      if (!selectedOpeningId.value && !selectedEndingId.value) {
        ElMessage.warning('请至少选择一个片头或片尾视频');
        return;
      }

      processing.value = true;
      try {
        const result = await introOutroService.processFolderIntroOutro(
          folderPath.value,
          outputFolder.value || undefined,
          selectedOpeningId.value || null,
          selectedEndingId.value || null,
          transitionEffect.value
        );

        processResult.value = result;

        if (result.success) {
          ElMessage.success('视频处理成功');
        } else {
          ElMessage.error(`处理失败: ${result.message || '未知错误'}`);
        }
      } catch (error) {
        ElMessage.error(`处理视频时发生错误: ${error.message || '未知错误'}`);
        processResult.value = {
          success: false,
          message: error.message || '处理过程中发生错误'
        };
      } finally {
        processing.value = false;
      }
    };

    // 清除结果
    const clearResult = () => {
      processResult.value = null;
    };

    onMounted(() => {
      loadTransitionEffects();
    });

    return {
      folderPath,
      outputFolder,
      transitionEffect,
      transitionEffects,
      selectedOpeningId,
      selectedEndingId,
      selectedOpeningVideo,
      selectedEndingVideo,
      processing,
      processResult,
      canProcess,
      handleOpeningSelection,
      handleEndingSelection,
      handleVideoDeleted,
      handleVideoSetDefault,
      processVideos,
      clearResult,
      copyFolder,
      fallbackCopyToClipboard,
      showManualCopyDialog,
    };
  }
});
</script>

<style scoped>
.intro-outro-view {
  padding: 20px 0;
}

h1 {
  margin-bottom: 20px;
  color: #303133;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #606266;
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.video-selection-row {
  margin-bottom: 20px;
}

.upload-card {
  height: 100%;
}

.process-actions {
  display: flex;
  justify-content: center;
  margin: 30px 0;
}

.result-card {
  margin-top: 30px;
}

.result-info {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}
</style>